package com.srs.dao.cfg;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.srs.dao.agent.AgentDao;
import com.srs.model.agent.Agent;
import com.srs.model.cfg.Country;
import com.srs.util.HibernateUtil;

public class CountryDao {

	final static Logger logger = LoggerFactory.getLogger(CountryDao.class);

	private List<Country> countryList;
	private Country country;

	public void delete(Integer countryId) {

		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			country = (Country) session.get(Country.class, countryId);
			session.delete(country);
			tx.commit();

		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Country> list() {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			countryList = session.createQuery("from Country").list();
			return countryList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}

	public Country get(Integer countryId) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			// change query for get proper data
			Query q = session.createQuery("from Country c where c.countryId=:countryId");
			q.setInteger("countryId", countryId);
			return (Country) q.uniqueResult();
		} finally {
			session.close();
		}

	}

	public void insert(Country country) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(country);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

	public void update(Country country) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(country);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

	public static void main(String[] args) {
		// Init sessionFactory
		SessionFactory sessionFactory = new Configuration().configure()
				.buildSessionFactory();
		HibernateUtil.setSessionFactory(sessionFactory);

		// Get list params
		AgentDao dao = new AgentDao();
		List<Agent> agents = dao.list();
		System.out.println(agents);
	}
}
